package com.jy.print.javaprint.utils;

import java.awt.image.BufferedImage;

import com.jy.print.javaprint.pojo.ProviderData;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.WidthCodedPainter;


public class AllotPrint {

    //    private Display uiDisplay;
    private ProviderData providerData;

    private Font font;
    private Font font1;
    private Color foregroundColor, backgroundColor;

    private Printer printer;
    private GC gc;

    private int lineHeight = 0;
    private int leftMargin, rightMargin, topMargin, bottomMargin;
    private Point dpi;

    private int x, y;

    private boolean printerFinish;

    public AllotPrint( ProviderData providerData) {
        this.providerData = providerData;
    }

    public void doPrint() {
        PrinterData[] printerList = Printer.getPrinterList();
        String printName = "Deli DL-888D";
        for (int i = 0; i < printerList.length; i++) {
//			if (printerList[i].name.equals("TSC TTP-244 #100")) {
            if (printerList[i].name.equals(printName)) {
//			if (printerList[i].name.equals("OPOS PS306")) {
                printerFinish = false;
                printerList[i].copyCount = 1;
                //printerList[i].orientation = PrinterData.PORTRAIT;
                //printerList[i].scope = PrinterData.ALL_PAGES;
                printer = new Printer(printerList[i]);
                Thread printingThread = new Thread("Printing") {
                    public void run() {
                        try {
                            try {

                                print(printer);
                                printer.dispose();
                            } finally {
                                printerFinish = true;
                                synchronized (this) {
                                    this.notifyAll();
                                }
                            }
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        } catch (Throwable e) {
                            System.out.println(e.getMessage());
                        }
                    }
                };
                printingThread.start();

//                while (!printerFinish) {
////                    if (!uiDisplay.readAndDispatch())
////                        uiDisplay.sleep();
//                }
                break;
            }
        }
    }

    void print(Printer printer) {
        if (printer.startJob("Text")) { // the string is the job name - shows up in the printer's job list
            Rectangle clientArea = printer.getClientArea();
            Rectangle trim = printer.computeTrim(0, 0, 0, 0);
            dpi = printer.getDPI();

            leftMargin = trim.x; // one inch from left side of paper
            rightMargin = clientArea.width + trim.x + trim.width; // one inch from right side of paper
            topMargin = trim.y; // one inch from top edge of paper
            bottomMargin = clientArea.height + trim.y + trim.height; // one inch from bottom edge of paper

            gc = new GC(printer);
            try {
                try {
                    font = new Font(printer, "宋体", 8, SWT.BOLD);
                    font1 = new Font(printer, "宋体", 7, SWT.BOLD);
                    foregroundColor = printer.getSystemColor(SWT.COLOR_BLACK);
                    backgroundColor = printer.getSystemColor(SWT.COLOR_WHITE);

                    gc.setFont(font);
                    lineHeight = gc.getFontMetrics().getHeight() + 2;
                    gc.setForeground(foregroundColor);
                    gc.setBackground(backgroundColor);

                    printContent();

                    printer.endJob();
                } finally {
                    if (font != null) {
                        font.dispose();
                        font = null;
                    }
                    if (font1 != null) {
                        font1.dispose();
                        font1 = null;
                    }
                    if (foregroundColor != null) {
                        foregroundColor.dispose();
                        foregroundColor = null;
                    }
                    if (backgroundColor != null) {
                        backgroundColor.dispose();
                        backgroundColor = null;
                    }
                }
            } finally {
                gc.dispose();
            }
        }
    }

    void printContent() {
        int linespace = 10;//(int) ((1d * dpi.y) / 25.4d) ;
        int left = 20;//(int) (rightMargin - (66d * dpi.x) / 25.4d);

        printer.startPage();
        printGd(linespace, left);
        printer.endPage();
//
//        printer.startPage();
//        printGd(linespace, left);
//        printer.endPage();
//
//        if (providerData.isNeedXqdy()) {
//            printer.startPage();
//            printGd(linespace, left);
//            printer.endPage();
//        }
    }


    private void printGd(int linespace, int left) {
        gc.setFont(font);


        y = 20;//(int) (topMargin + (11d * dpi.x) / 25.4d);
        x = left;
        int wordWidth = gc.stringExtent("供血浆者卡号：").x;
//		gc.setFont(new Font(printer, "宋体", 12, SWT.BORDER));
        gc.drawString("供血浆者卡号：" + providerData.getProviderNo(), x, y, false);

        x = left;
        y += lineHeight;
        y += linespace;
        gc.drawString("姓名：" + providerData.getName(), x, y, false);

        gc.drawString("性别：" + providerData.getSex(), x + wordWidth, y, false);

//		x = left;
//		y += lineHeight;
//		y += linespace;
//		gc.drawString("登记号：" + providerData.getIdx(), x, y, false);


//		if (!providerData.isNeedXqdy()) {
//			if (providerData.isNeedAssay()) {
//				gc.drawString("采前检", x + wordWidth, y, false);
//			} else {
//				gc.drawString("采后检", x + wordWidth, y, false);
//			}
//		}

        x = left;
        y += lineHeight;
        y += linespace;
        try {
            JBarcode jBarcode = new JBarcode(Code128Encoder.getInstance(), WidthCodedPainter.getInstance(), BaseLineTextPainter.getInstance());

            jBarcode.setShowCheckDigit(true);
            jBarcode.setCheckDigit(true);
            jBarcode.setShowText(false);

            jBarcode.setBarHeight(30d);
            jBarcode.setWideRatio(20d);
            jBarcode.setXDimension(0.8d);

            String str = providerData.getProviderNo();

            int destWidth = (int) ((32d * dpi.x) / 25.4d);
            int destHeight = (int) (8d * dpi.y / 25.4d);

            BufferedImage bImage = jBarcode.createBarcode(str);
            ImageData imageData = BufImgToMat.getImageData(bImage);
            Image image = new Image(printer, imageData);
            try {
                int vw = imageData.width;
                int vh = imageData.height;

                int destX = x + 10;
                int destY = y + 10;

                gc.drawImage(image, 0, 0, vw, vh, destX, destY, destWidth, destHeight);

                y += destHeight;
            } finally {
                image.dispose();
            }
        } catch (Exception localException) {
            localException.printStackTrace();
        }

        x = left;
        y += lineHeight;
        gc.setFont(new Font(printer, "宋体", 12, SWT.BOLD));
        gc.drawString("采浆机号：" + providerData.getMachineCode() + "号机", x, y, false);


        if (providerData.isNeedXqdy()) {
            gc.setFont(font1);
            x = left + 10;
            y += linespace;
            y += lineHeight + 5;
            gc.drawString("做血清电泳：" + providerData.getXqdyId(), x, y, false);
        }
    }
}
